package com.hnxxxy.rewardmgr.controller;

import cn.hutool.core.date.DateUtil;
import com.hnxxxy.common.tools.AppFileUtils;
import com.hnxxxy.rewardmgr.utils.UploadUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 袁峰
 * @Date 2021/1/2 14:51
 */
@RestController
@RequestMapping("file")
public class FileController {

    private static final String IMG_PATH = "/upload/img/";

    /**
     * 文件下载
     */
    @RequestMapping("showImageByPath")
    public ResponseEntity<Object> showImageByPath(String path) {
        ///upload/img/2021-01-06/E3FC668F09E0402DB2B7578CFE92627D.jpg
        return AppFileUtils.createResponseEntity(path);
    }

    /**
     * 文件上传
     */
    @RequestMapping("uploadFile")
    public Map<String, Object> uploadFile(MultipartFile mf) {

        //1、得到文件名
        String oldName = mf.getOriginalFilename();
        //2、根据文件名生成新文件名
        String newName = AppFileUtils.createNewFileName(oldName);
        //3,得到当前日期的字符串
        String dirName = DateUtil.format(new Date(), "yyyy-MM-dd");
        //4、构造文件夹
        File dirFile = new File(UploadUtils.getImgDirFile("img").getAbsolutePath() + IMG_PATH, dirName);
        System.out.println("上传=====》" + dirFile.getAbsolutePath());
        //5,判断当前文件夹是否存在
        if (!dirFile.exists()) {
            dirFile.mkdirs();//创建新的文件夹
        }
        //6,构造文件对象
        File file = new File(dirFile, newName + "_temp");
        System.out.println(file);
        //7,把mf里面的图片信息写入file
        try {
            mf.transferTo(file);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("path",IMG_PATH + dirName + "/" + newName + "_temp");
        return map;
    }
}
